package com.xqy.wexmini.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xqy.wexmini.constant.Constant;
import com.xqy.wexmini.domain.UUser;
import com.xqy.wexmini.domain.User;
import com.xqy.wexmini.domain.Vegetable;
import com.xqy.wexmini.mapper.VegetableMapper;
import com.xqy.wexmini.service.AuthService;
import com.xqy.wexmini.service.dto.AuthUserDto;
import com.xqy.wexmini.utils.JwtTokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@Api(tags = "微信号登录")
public class LoginController {
    @Autowired
    AuthService authService;
    @Autowired
    JwtTokenUtils jwtTokenUtils;
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Autowired
    private VegetableMapper vegetableMapper;

    @ApiOperation("登录授权")
    @PostMapping(value = "/login")
    public ResponseEntity login(@RequestBody AuthUserDto authUserDto, HttpServletRequest request){
        return ResponseEntity.ok(authService.login(authUserDto,request));
    }


/*    @ApiOperation("创建索引")
    @PostMapping(value="/a")*/
    public String a(String index) throws IOException {
        //1.创建索引请求
        CreateIndexRequest request = new CreateIndexRequest(Constant.VEGETABLE);//索引必须是小写这个bug检查了一下午长点记性
        //2.执行创建请求IndicesClient,请求后获得响应
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
        return "成功";
    }

/*    @ApiOperation("判断索引是否存在")
    @PostMapping(value = "/b")*/
    public String b(String index) throws IOException {
        GetIndexRequest request = new GetIndexRequest(Constant.VEGETABLE);
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
        return "成功";
    }
/*
    @ApiOperation("批量插入文档")
    @PostMapping(value = "/c")*/
    public String c(String index) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        List<Vegetable> list = vegetableMapper.selectList(null);

        //批处理请求
        for(int i=0;i<list.size();i++){

            //批量更新和批量删除就在这里修改对应的请求就可以了
            bulkRequest.add(
                    new IndexRequest(Constant.VEGETABLE)
                            //.id(""+(i+1))//如果不写这个生成的id就是随机的，但是重复无序，注意：如果id重复的话会覆盖
                            .source(JSON.toJSONString(list.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.hasFailures()); //是否失败，false就是执行成功
        return "成功";
    }
/*    @ApiOperation("指定蔬菜名称字段和索引搜索")
    @PostMapping(value = "/d")*/
    public String d(String name,String index) throws IOException {
        SearchRequest searchRequest = new SearchRequest(Constant.VEGETABLE);
        //构建搜索的条件（封装搜索的构建）
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //查询条件，我们可以使用QueryBuilder工具类来实现,构建查询的方式，还有构建高亮：HighlightBuilder
        //termQuery精确
        //matchAllQuery()匹配所有
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", name);
        sourceBuilder.query(matchQueryBuilder);//将查询的方式匹配给查询操作
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //将搜索条件放入请求里面
        searchRequest.source(sourceBuilder);
        //执行请求
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        SearchHit[] hits1 = hits.getHits();
        System.out.println(JSON.toJSONString(hits1[0]));
        String s = JSON.toJSONString(hits1[0]);

        return JSON.toJSONString(hits1[0]);
    }
}
